package arrAndstr;

import java.util.*;

/*
    49. 字母异位词分组
 */
public class T49 {
    public static void main(String[] args) {
        String[] strs = new String[]{
                "eat", "tea", "tan", "ate", "nat", "bat"
        };
        System.out.println(groupAnagrams(strs));
    }

    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();    // key为排序后的

        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String sortStr = String.valueOf(chars);

            if (!map.containsKey(sortStr)) {
                List<String> list = new ArrayList<>();
                list.add(str);
                map.put(sortStr, list);
            } else {
                List<String> list = map.get(sortStr);
                list.add(str);
                map.put(sortStr, list);
            }
        }

        List<List<String>> result = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            result.add(entry.getValue());
        }
        return result;
    }
}
